﻿using MES.Desktop.Entities;
using MES.Desktop.IDataAccess;
using MES.Desktop.IService;
using MES.Desktop.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MES.Desktop.Service
{
    public class MenuService : ServiceBase, IMenuService
    {
        IMenuAccess _menuAccess;
        public MenuService(IMenuAccess menuAccess)
        {
            _menuAccess = menuAccess;
        }
        public IEnumerable<MenuEntity> GetAllMenus(string key)
        {
            string json = _menuAccess.GetAllMenus(key);
            var result = JsonUtil.Deserializer<ApiDataResult<MenuEntity[]>>(json);
            if (result == null)
                throw new Exception("菜单数据获取失败!");
            if (!result.Success)
                throw new Exception(result.Message);

            return result.Data;
        }

        public IEnumerable<MenuEntity> GetMenuByRoles(int[] rid)
        {
            string json = JsonUtil.Serializer(rid);
            json = _menuAccess.GetMenuByRoles(json);
            var result = JsonUtil.Deserializer<ApiDataResult<MenuEntity[]>>(json);
            if (result == null)
                throw new Exception("菜单数据获取失败!");
            if (!result.Success)
                throw new Exception(result.Message);

            return result.Data;
        }

        public int UpdateMenu(MenuEntity menu)
        {
            string menu_json = System.Text.Json.JsonSerializer.Serialize(menu);
            string json = _menuAccess.UpdateMenu(menu_json);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("菜单数据获取失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未更新任何数据");

            return result.Data;
        }

        public int DeleteMenu(string id)
        {
            string json = _menuAccess.DeleteMenu(id);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("菜单数据获取失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未更新任何数据");

            return result.Data;
        }

        public int DeleteMenus(string[] ids)
        {
            string ids_json = System.Text.Json.JsonSerializer.Serialize(ids);
            string json = _menuAccess.DeleteMenus(ids_json);
            var result = JsonUtil.Deserializer<ApiDataResult<int>>(json);

            if (result == null)
                throw new Exception("菜单数据删除失败!");
            if (!result.Success)
                throw new Exception(result.Message);
            if (result.Data == 0)
                throw new Exception("未删除任何数据");

            return result.Data;
        }
    }
}
